<script setup>
  import {
    GetDataTypeDdlAPI,
    AddModeDataAPI,
    GetDataModeListAPI,
    GetDataModeViewAPI,
    EditDataModeAPI,
    DelDataModeAPI,
  } from "@/api/device/equipment.js";

  const { proxy } = getCurrentInstance();
  /**
   * 传入数据
   */
  const props = defineProps({
    data: Object,
    default: () => { },
  });

  /**
   * 列表枚举
   */
  const columns = ref([
    //   { label: "功能类型", prop: "deviceName" },
    { label: "功能名称", prop: "attributeName" },
    { label: "描述", prop: "description" },
    { label: "单位", prop: "unit" },
    { label: "标识符", prop: "identifier" },
    { label: "数据类型", prop: "dataType" },
    { label: "数据定义", prop: "specsData" },
    { label: "操作", prop: "x" },
  ]);

  /**
   * 各种状态
   */
  const state = reactive({
    title: "新增",
    loading: false, // 表格加载状态
    total: 0, // 列表总数量
    ids: [], // 勾选id
    rows: [], // 勾选数据
    btnLoading: false, // 保存按钮加载
    isShow: false, // 弹窗
    singleDis: false, // 多选后禁用
    multipleDis: false, // 没有选择后禁用
  });

  /**
   * 表单实例
   */
  const ruleFormRef = ref(null);

  /**
   * 表单
   */
  const ruleForm = ref({});

  const identifierValid = (rule, value, callback) => {
    if (!value) {
      callback(new Error("请填写表示字符"));
    } else {
      console.log(value, "valeu");

      let regex = /^[a-zA-Z][a-zA-Z0-9-_]*$/;
      if (!regex.test(value)) {
        callback(new Error("不能为中文，首字母不能为数字和特殊符号"));
      } else {
        callback();
      }
    }
  };

  /**
   * 字段校验
   */
  const rules = reactive({
    attributeName: [{ required: true, message: "请填写名称", trigger: "blur" }],
    identifier: [
      {
        required: true,
        // message: '请填写标识符',
        trigger: "blur",
        validator: identifierValid,
      },
    ],
    dataType: [{ required: true, message: "请选择数据类型", trigger: "change" }],
    source: [{ required: true, message: "请填写数据源", trigger: "change" }],
    ratio: [{ required: true, message: "请填写比例", trigger: "change" }],
  });

  /**
   * 分页参数
   */
  const query = reactive({
    pageNum: 1,
    pageSize: 10,
  });

  /**
   * 列表数据
   */
  const tableData = ref([]);

  /**
   * 数据类型下拉
   */
  const dataTypeList = ref([]);

  /**
   * 判断处理数据
   */
  const whereData = async () => {
    if (ruleForm.value.dataType == 5 || ruleForm.value.dataType == 6) {
      ruleForm.value.specs = {};
    }

    // 数据类型为枚举时 map转对象
    if (ruleForm.value.dataType == 3) {
      ruleForm.value.specs = JSON.stringify(ruleForm.value.specsArr);
    } else {
      ruleForm.value.specs = JSON.stringify(ruleForm.value.specs);
    }

    ruleForm.value.deviceKey = props.data.deviceKey;
    ruleForm.value.deviceId = props.data.id;
  };

  /**
   * 修改弹窗
   */
  const editDic = async (id) => {
    getDataTypeDdl();
    try {
      proxy.loading("请求中，请稍后");
      const { data: result } = await GetDataModeViewAPI(id);
      ruleForm.value = result;
      ruleForm.value.dataTypeT = result.dataType;
      ruleForm.value.specsArr = JSON.parse(result.specs);
      ruleForm.value.specs = JSON.parse(result.specs);
      state.isShow = true;
      state.title = "修改";
    } catch (err) {
      console.error(err);
    } finally {
      proxy.closeLoading();
    }
  };

  /**
   * 新增
   */
  const physicalModelAddSub = async () => {
    try {
      await ruleFormRef.value.validate();

      if (ruleForm.value.dataType == 2) {
        if (!ruleForm.value.specs["0"] || !ruleForm.value.specs["1"]) {
          proxy.errorMsg("布尔值为必填");
          return;
        }
      }
      console.log(ruleForm.value, "ruleForm.value");
      if (ruleForm.value.dataType == 3) {
        if (ruleForm.value.specsArr.length == 0) {
          proxy.errorMsg("枚举值必须有一条数据");
          return;
        }

        if (ruleForm.value.specsArr?.filter((t) => t.value.length) == 0)
          return proxy.errorMsg("枚举描述为必填");
        if (ruleForm.value.specsArr?.filter((t) => t.key).length == 0)
          return proxy.errorMsg("枚举值为必填");
      }
      whereData();
      state.btnLoading = true;
      await AddModeDataAPI(ruleForm.value);
      state.isShow = false;
      close();
      getList();
      proxy.successMsg("新增成功");
    } catch (err) {
      console.log(err);
    } finally {
      state.btnLoading = false;
    }
  };

  /**
   * 修改提交
   */
  const physicalModelEditSub = async () => {
    try {
      await ruleFormRef.value.validate();
      whereData();

      if (ruleForm.value.dataType == 2) {
        if (!ruleForm.value.specs["0"] || !ruleForm.value.specs["1"]) {
          proxy.errorMsg("布尔值为必填");
        }
      }
      if (ruleForm.value.dataType == 3) {
        if (ruleForm.value.specsArr.length == 0) {
          proxy.errorMsg("枚举值必须有一条数据");
          return;
        }

        if (ruleForm.value.specsArr?.filter((t) => t.value.length) == 0)
          return proxy.errorMsg("枚举描述为必填");
        if (ruleForm.value.specsArr?.filter((t) => t.key).length == 0)
          return proxy.errorMsg("枚举值为必填");
      }
      state.btnLoading = true;
      await EditDataModeAPI(ruleForm.value);
      state.isShow = false;
      close();
      proxy.successMsg("修改成功");
      getList();
    } catch {
    } finally {
      state.btnLoading = false;
    }
  };

  /**
   * 删除
   * @param {*} id  数据id
   */
  const remove = async (id) => {
    try {
      proxy.loading("删除中,请稍后...");
      await DelDataModeAPI(id);
      proxy.successMsg("删除成功");
      getList();
    } catch (err) {
      console.error(err);
    } finally {
      proxy.closeLoading();
    }
  };

  /**
   * 数据类型改变 0:int32 1:float 2:bool 3:enum 4:text 5:data
   * @param {*} val 当前选中值
   */
  const dataTypeListChange = (val) => {
    // enum为数组 多个
    if (val == 3) {
      ruleForm.value.specsArr = [
        {
          key: "",
          value: "",
        },
      ];
    }
    // int32和float为对象 key为min max
    if (val == 0 || val == 1) {
      ruleForm.value.specs = {
        min: "",
        max: "",
      };
    }
    if (val == 2) {
      ruleForm.value.specs = {
        0: "",
        1: "",
      };
    }

    ruleForm.value.dataType = val;
  };

  /**
   * 获取数据类型下拉
   */
  const getDataTypeDdl = async () => {
    try {
      const result = await GetDataTypeDdlAPI();
      dataTypeList.value = result.data;
    } catch {
    } finally {
    }
  };

  /**
   * 数据类型为 enum 时 添加枚举
   */
  const addEnum = () => {
    ruleForm.value.specsArr.push({
      key: "",
      value: "",
    });
  };

  /**
   * 数据类型为 enum 时 枚举删除
   * @param {*} i
   */
  const delEnum = (i) => {
    ruleForm.value.specsArr.splice(i, 1);
  };

  /**
   * 弹窗关闭
   */
  const close = () => {
    state.isShow = false;
    // ruleForm.value.specs = "";
    // ruleForm.value.identifier = "";
    // ruleForm.value.attributeName = "";

    ruleForm.value = {
      dataTypeT: "",
    };
  };

  /**
   * 获取列表
   */
  const getList = async () => {
    state.loading = true;
    try {
      const result = await GetDataModeListAPI({ deviceId: props.data.id });
      tableData.value = result.data;
    } catch {
    } finally {
      state.loading = false;
    }
  };
  getList();

  const num = ref(0);

  /**
    新增
     */
  const add = () => {
    state.isShow = true;
    // num.value++;
    // ruleForm.value.attributeName = `温度${num.value}`;
    // ruleForm.value.identifier = `temp${num.value}`;
    state.title = "新增";
    getDataTypeDdl();
  };
</script>

<template>
  <div class="app-container">
    <el-button icon="Plus" type="primary" @click="add">新增</el-button>

    <p-table :loading="state.loading" keyId="id" :column="columns" :data="tableData" :isSel="false"
      @pagination="getList">
      <template #columnCell="{ column, record }">
        <div v-if="column.label == '数据定义'" style="cursor: pointer">
          <el-popover placement="right" :width="400" trigger="hover">
            <template #reference>
              <p>{{ record.specsData }}</p>
            </template>
            <p>{{ record.specsData }}</p>
          </el-popover>
        </div>
        <p-operate v-if="column.prop == 'x'" :list="[
            {
              icon: 'edit',
              emit: 'edit',
              text: '修改',
              type: 'primary',
              hasPermi: 'device:equipment:edit',
            },
            {
              icon: 'DeleteFilled',
              emit: 'remove',
              text: '删除',
              isDel: true,
              type: 'danger',
              hasPermi: 'device:equipment:query',
            },
          ]" @edit="editDic(record.id)" @look="lookDic(record.id)" @remove="remove(record.id)" />
      </template>
    </p-table>
    <!-- 新增 -->
    <p-dialog v-model="state.isShow" :title="state.title" :loading="state.btnLoading" @close="close" @ok="
        state.title == '新增' ? physicalModelAddSub() : physicalModelEditSub()
      " width="50%">
      <el-form ref="ruleFormRef" inline :model="ruleForm" :rules="rules" label-width="120px" status-icon>
        <el-form-item label="名称" prop="attributeName" style="margin-bottom: 30px">
          <el-input :disabled="props.disabled" clearable v-model="ruleForm.attributeName" />
        </el-form-item>
        <el-form-item label="标识符" prop="identifier" style="margin-bottom: 30px">
          <el-input :disabled="props.disabled" clearable v-model="ruleForm.identifier" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input :disabled="props.disabled" clearable v-model="ruleForm.description" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input :disabled="props.disabled" clearable v-model="ruleForm.unit" />
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <p-select :disabled="props.disabled" clearable :option="dataTypeList" @change="dataTypeListChange"
            v-model="ruleForm.dataTypeT" />
        </el-form-item>
        <el-form-item label="数据源" prop="source">
          <el-input :disabled="props.disabled" clearable v-model="ruleForm.source" />
        </el-form-item>
        <el-form-item label="比例" prop="ratio" v-if="ruleForm.dataType == 1">
          <el-input-number :min="0" :controls="false" :disabled="props.disabled" clearable v-model="ruleForm.ratio" />
        </el-form-item>
      </el-form>
      <!-- int32 -->
      <div class="formItem" v-if="ruleForm.dataType == 0">
        <div class="label">取值范围</div>
        <el-input v-model="ruleForm.specs.min" placeholder="最小值" />-
        <el-input v-model="ruleForm.specs.max" placeholder="最大值" />
      </div>
      <!-- float -->
      <div class="formItem" v-if="ruleForm.dataType == 1">
        <div class="label">取值范围</div>

        <el-input v-model="ruleForm.specs.min" placeholder="最小值" />-
        <el-input v-model="ruleForm.specs.max" placeholder="最大值" />
      </div>
      <!-- bool -->
      <div class="formItem" v-if="ruleForm.dataType == 2">
        <div class="label">布尔值</div>

        <el-input v-model="ruleForm.specs['0']" placeholder="如:否" />-
        <el-input v-model="ruleForm.specs['1']" placeholder="如:是" />
      </div>
      <!-- enum -->
      <template v-if="ruleForm.dataType == 3">
        <div class="formItem" style="margin-bottom: 10px" v-for="(t, i) in ruleForm.specsArr" :key="i">
          <div class="label">枚举值</div>
          <el-input v-model="t.key" placeholder="如:0" style="width: 80px" />
          <div class="formItem" style="margin-left: 20px">
            <div class="label">枚举描述</div>
            <el-input v-model="t.value" />
            <el-button type="danger" icon="delete" style="margin-left: 10px" @click="delEnum(i)" />
          </div>
        </div>

        <el-button class="formItem" type="primary" @click="addEnum">添加</el-button>
      </template>
    </p-dialog>
  </div>
</template>
<style scoped lang="scss">
  .formItem {
    display: flex;
    align-items: center;
    margin-left: 140px;
  }

  .label {
    width: 140px;
  }
</style>